
/**
 * Date:2019年5月31日下午4:38:19
 * Copyright (c) 2019, www.bwbroad.com All Rights Reserved.
 *
*/

package com.xue.im.common.coder;

import java.io.IOException;

import org.jboss.marshalling.ByteInput;

import io.netty.buffer.ByteBuf;

/**
 * Description: TODO <br/>
 * Date: 2019年5月31日 下午4:38:19 <br/>
 * 
 * @author xuejianxin
 */
public class MyChannelBufferByteInput implements ByteInput {

	private final ByteBuf buffer;

	MyChannelBufferByteInput(ByteBuf buffer) {
		this.buffer = buffer;
	}

	@Override
	public void close() throws IOException {
		// nothing to do
	}

	@Override
	public int available() throws IOException {
		return buffer.readableBytes();
	}

	@Override
	public int read() throws IOException {
		if (buffer.isReadable()) {
			return buffer.readByte() & 0xff;
		}
		return -1;
	}

	@Override
	public int read(byte[] array) throws IOException {
		return read(array, 0, array.length);
	}

	@Override
	public int read(byte[] dst, int dstIndex, int length) throws IOException {
		int available = available();
		if (available == 0) {
			return -1;
		}

		length = Math.min(available, length);
		buffer.readBytes(dst, dstIndex, length);
		return length;
	}

	@Override
	public long skip(long bytes) throws IOException {
		int readable = buffer.readableBytes();
		if (readable < bytes) {
			bytes = readable;
		}
		buffer.readerIndex((int) (buffer.readerIndex() + bytes));
		return bytes;
	}

}